package com.module.retrofit.interceptor;

import android.util.Log;

import com.module.retrofit.utils.NetUtil;
import com.module.retrofit.ApplicationHelper;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by dell on 2017/2/23
 */

public class CacheInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if(!NetUtil.isNetworkConnected(ApplicationHelper.getContext())){
            Log.e("CacheInterceptor", "访问缓存request");
            //访问缓存
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }else{
            //访问网络
            Log.e("CacheInterceptor", "访问网络request");
        }

        Response response = chain.proceed(request);
        if(!NetUtil.isNetworkConnected(ApplicationHelper.getContext())){
            //访问缓存
            Log.e("CacheInterceptor", "访问缓存response");
            int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
            response.newBuilder()
                    .removeHeader("Pragma") //清除响应体对Cache有影响的信息
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }else{
            //访问网络
            Log.e("CacheInterceptor", "访问网络response");
            int maxAge = 0 * 60; // 有网络时 设置缓存超时时间0个小时
            response.newBuilder()
                    .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        }
        return response;
    }


}
